<template>
  <div class="schedule-container">
    <h1>生产计划管理</h1>

    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="query" label-width="100px" inline>
        <el-form-item label="生产订单">
          <el-select v-model="query.production_order_id" placeholder="选择生产订单" clearable>
            <el-option
                v-for="order in productionOrders"
                :key="order.id"
                :label="order.id + ' - ' + (order.product_name || '未知产品')"
                :value="order.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分配员工">
          <el-select v-model="query.assigned_employee_id" placeholder="选择员工" clearable>
            <el-option
                v-for="emp in employees"
                :key="emp.id"
                :label="emp.id + ' - ' + emp.name"
                :value="emp.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSchedules">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="openAddDialog">新增生产计划</el-button>
    </div>

    <!-- 表格 -->
    <el-table
        :data="pagedData"
        border
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="production_order_id" label="生产订单ID" width="150" />
      <el-table-column label="计划开始时间" width="150">
        <template #default="scope">{{ formatDate(scope.row.scheduled_start) }}</template>
      </el-table-column>
      <el-table-column label="计划结束时间" width="150">
        <template #default="scope">{{ formatDate(scope.row.scheduled_end) }}</template>
      </el-table-column>
      <el-table-column prop="assigned_employee_id" label="分配员工ID" width="150" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="confirmDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-if="tableData.length > 0"
        background
        layout="prev, pager, next, sizes, total"
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="tableData.length"
        @current-change="(val) => (page = val)"
        @size-change="(val) => { pageSize = val; page = 1; }"
        style="margin-top: 20px; justify-content: center;"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="editForm.id ? '编辑生产计划' : '新增生产计划'"
        width="500px"
    >
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="生产订单" required>
          <el-select v-model="editForm.production_order_id" placeholder="选择生产订单">
            <el-option
                v-for="order in productionOrders"
                :key="order.id"
                :label="order.id + ' - ' + (order.product_name || '未知产品')"
                :value="order.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划开始时间" required>
          <el-date-picker
              v-model="editForm.scheduled_start"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择开始时间"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="计划结束时间" required>
          <el-date-picker
              v-model="editForm.scheduled_end"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择结束时间"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="分配员工">
          <el-select v-model="editForm.assigned_employee_id" placeholder="选择员工">
            <el-option
                v-for="emp in employees"
                :key="emp.id"
                :label="emp.id + ' - ' + emp.name"
                :value="emp.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import productionScheduleApi from '../api/productionScheduleApi.js';
import employeeApi from '../api/employeeapi.js';
import productionOrderApi from '../api/productionOrderApi.js';

// 数据
const tableData = ref([]);
const employees = ref([]);
const productionOrders = ref([]);
const loading = ref(false);

// 分页
const page = ref(1);
const pageSize = ref(5);
const pagedData = computed(() => {
  const start = (page.value - 1) * pageSize.value;
  return tableData.value.slice(start, start + pageSize.value);
});

// 查询条件
const query = reactive({ production_order_id: null, assigned_employee_id: null });

// 编辑对话框
const dialogVisible = ref(false);
const editForm = reactive({ id: null, production_order_id: null, scheduled_start: '', scheduled_end: '', assigned_employee_id: null });

// 格式化日期
const formatDate = (dateString) => dateString ? new Date(dateString).toISOString().split('T')[0] : '';

// 加载列表
const loadSchedules = async () => {
  loading.value = true;
  try {
    const res = await productionScheduleApi.list();
    tableData.value = res && res.code === 200 && Array.isArray(res.data) ? res.data : [];
    page.value = 1;
  } catch (err) {
    console.error('加载失败:', err);
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

// 查询
const searchSchedules = async () => {
  loading.value = true;
  try {
    const res = await productionScheduleApi.list(query);
    tableData.value = res && res.code === 200 && Array.isArray(res.data) ? res.data : [];
    page.value = 1;
  } catch (err) {
    console.error('查询失败:', err);
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};
const resetSearch = () => { query.production_order_id = null; query.assigned_employee_id = null; loadSchedules(); };

// 打开新增/编辑
const openAddDialog = () => { Object.assign(editForm, { id: null, production_order_id: null, scheduled_start: '', scheduled_end: '', assigned_employee_id: null }); dialogVisible.value = true; };
const openEditDialog = (schedule) => { Object.assign(editForm, schedule); dialogVisible.value = true; };

// 保存
const submitEdit = async () => {
  if (!editForm.production_order_id || !editForm.scheduled_start || !editForm.scheduled_end) return ElMessage.warning('请填写必填字段');
  try {
    if (editForm.id) await productionScheduleApi.edit(editForm);
    else await productionScheduleApi.add(editForm);
    dialogVisible.value = false;
    loadSchedules();
    ElMessage.success('操作成功');
  } catch (err) {
    console.error(err);
    ElMessage.error('操作失败');
  }
};

// 删除
const confirmDelete = (id) => {
  ElMessageBox.confirm('确定要删除该生产计划吗？', '删除确认', { type: 'warning' })
      .then(async () => { await productionScheduleApi.del(id); ElMessage.success('删除成功'); loadSchedules(); })
      .catch(() => ElMessage.info('已取消删除'));
};

// 初始化
onMounted(() => { loadSchedules(); employeeApi.list().then(res => { if (res.code === 200) employees.value = res.data || []; }); productionOrderApi.list().then(res => { if (res.code === 200) productionOrders.value = res.data || []; }); });
</script>

<style scoped>
.schedule-container { padding: 20px; }
.search-card { margin-bottom: 20px; }
.toolbar { margin-bottom: 20px; text-align: right; }
</style>
